package com.example.bookmall.service.Captcha;


import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

@Service
public class CaptchaService {
    
    @Autowired
    private Producer captchaProducer;
    
    public String generateCaptchaCode() {
        return captchaProducer.createText();
    }
    
    public BufferedImage generateCaptchaImage(String captchaCode) {
        return captchaProducer.createImage(captchaCode);
    }
    
    public void storeCaptcha(HttpServletRequest request, String captchaCode) {
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaCode.toLowerCase());
        session.setAttribute("captchaExpire", System.currentTimeMillis() + 60000); // 1分钟过期
    }
    
    public boolean validateCaptcha(HttpServletRequest request, String inputCaptcha) {
        HttpSession session = request.getSession();
        String sessionCaptcha = (String) session.getAttribute("captcha");
        Long expireTime = (Long) session.getAttribute("captchaExpire");
        
        // 清除已使用的验证码
        session.removeAttribute("captcha");
        session.removeAttribute("captchaExpire");
        
        if (inputCaptcha == null || inputCaptcha.isEmpty() || sessionCaptcha == null) {
            return false;
        }
        
        if (expireTime == null || System.currentTimeMillis() > expireTime) {
            return false;
        }
        
        return inputCaptcha.toLowerCase().equals(sessionCaptcha);
    }
}